<template>
	<canvas class="hiddenCanvas" :style="{
			width:width + 'px',
			height:height + 'px'
		}" :canvas-id="canvasId" :id="canvasId"></canvas>
</template>l

<script>
	function uuid(len, radix) {
		var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
		var uuid = [],
			i;
		radix = radix || chars.length;

		if (len) {
			// Compact form
			for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
		} else {
			// rfc4122, version 4 form
			var r;

			// rfc4122 requires these characters
			uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
			uuid[14] = '4';

			// Fill in random data.  At i==19 set the high bits of clock sequence as
			// per rfc4122, sec. 4.1.5
			for (i = 0; i < 36; i++) {
				if (!uuid[i]) {
					r = 0 | Math.random() * 16;
					uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
				}
			}
		}

		return uuid.join('');
	}

	export default {
		name: 'easy-watermark',
		data() {
			return {
				canvasId: 'u' + uuid(8),
				// #ifdef MP-WEIXIN
				canvasId: 'canvasId',
				// #endif
				options: {
					fontSize: 14, //文字大小
					shortLength: 375, //短边的长度，长边将按照比例自动设置，设置为0时使用图片的原始长宽。
					padding: 10, //背景的内边距
					//margin: 0, //背景的外边距
					textGap: 6, //文字行距
					color: '#ffffff', //文字颜色
					bgColor: 'rgba(0,0,0,0.3)', //背景颜色
					waitTime: 50,
					showDot: true
				},
				width: 0,
				height: 0,
				textY: 10,
				textList: []
			}
		},
		mounted() {
			//console.log(this.canvasId);
			this.context = uni.createCanvasContext(this.canvasId, this)
			const info = uni.getDeviceInfo()
			//this.width *= info.devicePixelRatio
			//console.log(info.devicePixelRatio, this.width);
		},
		methods: {
			async addWatermark(url, textList, options) {
				try {
					this.options = {
						...this.options,
						...options
					}

					this.textY = this.options.padding

					console.log(this.options);

					this.textList = textList.slice(0).reverse()

					await this.getImageInfo(url)
					return await this.getImagePath()
				} catch (e) {
					console.log(e);
					return ''
				}
			},
			async getImageInfo(url) {

				const info = await uni.getImageInfo({
					src: url
				})

				console.log(info);
				this.clcuSize(info)

				return new Promise((resolve, reject) => {
					setTimeout(async () => {
						this.draw(url, resolve)
					}, this.options.waitTime)
				})
			},
			draw(path, callback) {
				const ctx = this.context

				const {
					padding,
					margin,
					fontSize,
					textGap,
					color,
					bgColor
				} = this.options

				console.log(this.width, this.height);

				ctx.drawImage(path, 0, 0, this.width, this.height)

				let length = this.textList.length
				let rectHeight = length * fontSize + (length - 1) * textGap + padding * 2
				let rectY = this.height - rectHeight
				ctx.setTextAlign('left')
				ctx.setFontSize(fontSize)
				ctx.setFillStyle(bgColor)
				ctx.fillRect(0, rectY, this.width, rectHeight)
				ctx.setFillStyle(color)
				ctx.setTextBaseline('top')

				this.textList.forEach(this.fillText)

				ctx.draw(false, callback)
			},
			async getImagePath() {
				let res = await uni.canvasToTempFilePath({
					canvasId: this.canvasId,
					// x: 0,
					// y: 0,
					// width: this.width,
					// height: this.height,
					// destWidth: this.width * 2,
					// destHeight: this.height * 2,
					fileType: 'jpg',
					quality: 0.5
				}, this)
				return res.tempFilePath
			},
			clcuSize(info) {
				const {
					shortLength
				} = this.options

				if (shortLength === 0) {
					this.width = info.width
					this.height = info.height
					this.fontSize = 14 / 375 * this.width
				} else if (info.width < info.height) {
					this.width = shortLength
					this.height = this.width / (info.width / info.height)
				} else {
					this.height = shortLength
					this.width = this.height / (info.height / info.width)
				}
			},
			fillText(text) {

				const {
					padding,
					margin,
					fontSize,
					textGap,
					showDot
				} = this.options

				const {
					context,
					width,
					height,
					textY
				} = this

				//const metrics = context.measureText(text)
				//console.log(height, textY, fontSize);
				let fillY = height - textY - fontSize
				//console.log(fillY);
				this.textY = height - fillY + textGap
				const dot = showDot ? '•  ' : ''
				context.fillText(dot + text, padding, fillY)
			}
		}
	}
</script>

<style>
	.hiddenCanvas {
		z-index: -1;
		left: 100%;
		position: fixed;
		visibility: hidden;
		opacity: 0;
	}
</style>